package cn.edu.hzu.graduation.config;

import org.eclipse.paho.client.mqttv3.IMqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfig {
    @Value("${mqtt.url}")
    String url;
    @Value("${mqtt.username}")
    String username;
    @Value("${mqtt.password}")
    String password;
    @Bean(destroyMethod = "disconnect")
    public IMqttClient defaultMqttClient() throws MqttException{
        String clientId = "sample-client-id";//客户端id，可自定义
        MemoryPersistence persistence = new MemoryPersistence();
        IMqttClient client = new org.eclipse.paho.client.mqttv3.MqttClient(url,clientId,persistence);
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setCleanSession(true);
        if(username != null && !username.isEmpty()){
            connectOptions.setUserName(username);
            connectOptions.setPassword(password.toCharArray());
        }
        client.connect(connectOptions);
        return client;
    }
}
